package websocket

import (
	"sync"
	"time"

	"github.com/gorilla/websocket"
	"gorm.io/gorm"
)

// WebSocket服务器
type WebSocketServer struct {
	Rooms    map[string]*Room
	Mu       sync.RWMutex
	upgrader websocket.Upgrader
	DB       *gorm.DB
	// 添加游戏相关字段
	GameRooms map[string]*GameRoom
	gameMu    sync.RWMutex
}

// Room 表示一个WebSocket房间
type Room struct {
	ID           string
	Name         string
	CreatorID    string
	CreatorName  string
	Clients      map[string]*Client
	UserNames    map[string]string
	JoinTimes    map[string]int64
	Ready        map[string]bool
	MaxUsers     int
	Mu           sync.RWMutex
	destroyTimer *time.Timer
	wsServer     *WebSocketServer
	Messages     []*Message
}

// GameRoom 表示一个游戏房间
type GameRoom struct {
	ID             string
	Name           string
	Type           string // snake, gomoku, tictactoe
	CreatorID      string
	CreatorName    string
	Clients        map[string]*Client
	UserNames      map[string]string
	JoinTimes      map[string]int64
	Ready          map[string]bool
	MaxUsers       int
	mu             sync.RWMutex
	destroyTimer   *time.Timer
	wsServer       *WebSocketServer
	GameState      *GameState
	gameTicker     *time.Ticker
	gameLoopTicker *time.Ticker
	stopGame       chan struct{}
	gameMu         sync.RWMutex
	Messages       []*Message // 消息历史记录
}

// Client 表示一个WebSocket客户端
type Client struct {
	UserID   string
	UserName string
	Conn     *websocket.Conn
	Send     chan []byte
	Mu       sync.Mutex
	sendClosed bool
}

// 消息类型常量
type MessageType int

const (
	MessageTypeJoin         MessageType = 1  // 加入房间
	MessageTypeLeave        MessageType = 2  // 离开房间
	MessageTypeText         MessageType = 3  // 文本消息
	MessageTypeReady        MessageType = 4  // 准备状态
	MessageTypeReadyChanged MessageType = 5  // 准备状态变更
	MessageTypeGameOp       MessageType = 6  // 游戏操作
	MessageTypeGameState    MessageType = 7  // 游戏状态
	MessageTypeGameStart    MessageType = 8  // 游戏开始
	MessageTypeGameEnd      MessageType = 9  // 游戏结束
	MessageTypeRead         MessageType = 10 // 消息已读
	MessageTypeSystem       MessageType = 99 // 系统消息
)

// Message 表示WebSocket消息
type Message struct {
	ID       string          `json:"id,omitempty"`
	Type     int             `json:"type"`
	UserID   string          `json:"user_id"`
	UserName string          `json:"user_name"`
	Content  string          `json:"content"`
	Time     int64           `json:"time"`
	RoomID   string          `json:"room_id,omitempty"`
	Data     interface{}     `json:"data,omitempty"`
	ReadBy   map[string]bool `json:"read_by,omitempty"`
}

// GameState 表示游戏状态
type GameState struct {
	Status    string                 `json:"status"` // waiting, playing, gameover
	StartTime int64                  `json:"start_time,omitempty"`
	EndTime   int64                  `json:"end_time,omitempty"`
	Snakes    map[string]*Snake      `json:"snakes,omitempty"`
	Foods     []SnakeSegment         `json:"foods,omitempty"`
	Scores    map[string]int         `json:"scores,omitempty"`
	Ready     map[string]bool        `json:"ready,omitempty"`
	Board     [][]int                `json:"board,omitempty"`
	Players   map[string]*PlayerInfo `json:"players,omitempty"`
}

// Snake 表示蛇游戏中的蛇
type Snake struct {
	Segments  []SnakeSegment `json:"segments"`
	Direction string         `json:"direction"`
	Alive     bool           `json:"alive"`
	Color     string         `json:"color,omitempty"`
}

// SnakeSegment 表示蛇的一段或食物的位置
type SnakeSegment struct {
	X int `json:"x"`
	Y int `json:"y"`
}

// PlayerInfo 表示玩家信息
type PlayerInfo struct {
	UserID   string `json:"user_id"`
	UserName string `json:"user_name"`
	Score    int    `json:"score,omitempty"`
	Ready    bool   `json:"ready,omitempty"`
	Color    string `json:"color,omitempty"`
	Alive    bool   `json:"alive,omitempty"`
}

// 玩家操作消息结构
type GameOp struct {
	Op       string `json:"op"`
	UserID   string `json:"user_id"`
	UserName string `json:"user_name,omitempty"`
	Dir      string `json:"dir,omitempty"`
	Ready    *bool  `json:"ready,omitempty"`
	X        int    `json:"x,omitempty"`
	Y        int    `json:"y,omitempty"`
}
